package com.mialab.servlet_demo;

import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "/SimpleAsyncServlet", urlPatterns = { "/simpleAsync" }, asyncSupported = true)
public class SimpleAsyncServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public SimpleAsyncServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		final AsyncContext asyncContext = request.startAsync();
		System.out.println(Thread.currentThread().getName());
		request.setAttribute("boyName", "李寻欢");
		asyncContext.setTimeout(6000);
		asyncContext.start(new Runnable() {
			@Override
			public void run() {
				try {
					int millis = ThreadLocalRandom.current().nextInt(3000);
					String currentThread = Thread.currentThread().getName();
					System.out.println(currentThread + " sleep for " + millis + " milliseconds.");
					Thread.sleep(millis);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				request.setAttribute("girlName", "我不是潘金莲");
				asyncContext.dispatch("/boygirl.jsp");
			}
		});
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

}
